<template>
    <view>
        <!-- 不固定车位的表单 -->
        <view>
            <view class="top-card">
                <van-cell-group>
                    <van-cell title="停车场">{{ datas.parkingName }}</van-cell>
                    <van-cell title="停车要求">{{ datas.parkingRequire == 1 ? '限小区居民' : '对公众开放' }}</van-cell>
                    <van-cell title="车位号">{{ fix == 1 ? '不固定车位号' : datas.spaceNo }}</van-cell>
                    <van-cell title="车位类型">{{ datas.spaceOwnerType == 1 ? '个人所有' : '企业经营' }}</van-cell>
                    <van-cell title="联系电话" v-if="datas.spaceOwnerType == 2">{{ datas.phone }}</van-cell>
                    <van-cell title="车场管理" v-if="datas.managementMethod != null">{{ datas.managementMethod == '0' ? '无人值守' : '有人值守' }}</van-cell>
                    <van-cell title="营业时间" v-if="datas.openTime != null">{{ datas.openTime || '24小时' }}</van-cell>
                    <van-cell title="可租时间">{{ datas.sumDuraTion }}个月</van-cell>
                </van-cell-group>
            </view>
            <view class="cell-btm">
                <van-cell title="我的车辆" is-link @click="showCarFun">
                    <span :class="carNo != '请选择' ? 'infoText' : ''">{{ carNo }}</span>
                </van-cell>
                <van-cell title="包月套餐" is-link @click="showSetmenuFun">
                    <span :class="selectedmenu != '请选择' ? 'infoText' : ''">{{ selectedmenu }}</span>
                </van-cell>
                <van-cell title="开始停车" is-link @click="showStartDateFun">
                    <span :class="parkTime != '请选择' ? 'infoText' : ''">{{ parkTime }}</span>
                </van-cell>
                <van-cell title="租赁期限" is-link @click="ShowRentPop">
                    <span :class="rentMonth != '请选择' ? 'infoText' : ''">{{ rentMonth }}</span>
                </van-cell>
            </view>
            <view class="rule">
                <van-checkbox v-model="checked" @change="onChange" checked-color="#00BCAB"></van-checkbox>
                <text @tap="showRule" style="padding-left: 10rpx">我已经阅读并同意《停车服务协议》</text>
            </view>
            <view class="btn" @tap="submit">确定预约</view>
            <view class="tip-btm">
                <view class="tip-title">温馨提示：</view>
                <view class="tip-content">
                    <view>1、若您需要提前结束租赁，请通过个人中心申请，并与车主协商和线下退款。</view>
                    <view>2、需要修改停车车辆信息，请到个人中心中修改。</view>
                </view>
            </view>
        </view>
        <view>
            <van-popup round v-model="showRulePop" @close="closeRule">
                <view class="rules">
                    <view class="rule-title">停车服务协议</view>
                    <!-- <view class="rule-content">
        {{platformRules}}
      </view> -->
                    <view class="rule-content"><rich-text :nodes="platformRules"></rich-text></view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule">我知道了</view>
                </view>
            </van-popup>
        </view>
        <!-- 车辆下拉 -->
        <van-popup v-model="showCar" position="bottom" @close="onCloseCar">
            <van-picker show-toolbar :columns="carList" @confirm="onSelectCar" @cancel="onCloseCar" />
        </van-popup>
        <!-- 套餐下拉 -->
        <van-popup v-model="showSetmenu" position="bottom" @close="onCloseMenu">
            <van-picker show-toolbar :columns="setMenu" @confirm="onSelectMenu" @cancel="onCloseMenu" />
        </van-popup>
        <!-- 开始停车 -->
        <van-popup v-model="showStartDate" @close="onCloseDatePop" position="bottom">
            <van-datetime-picker type="date" v-model="currentDate" :min-date="minDate" :max-date="maxDate" @confirm="SelectDate" @cancel="onCloseDatePop" />
        </van-popup>
        <!-- 租赁期限 -->
        <van-popup v-model="showRentmonth" @close="onCloseRentMonth" position="bottom">
            <van-picker show-toolbar :columns="columnsTime" @confirm="onChangeRentMonth" @cancel="onCloseRentMonth" />
        </van-popup>
        <van-dialog id="van-dialog" />
        <van-toast id="van-toast" />
        <van-dialog
            id="van-dialog2"
            v-model="showLink"
            title="该车场仅开通支付宝收款功能，请点击“复制链接”至系统浏览器打开，使用支付宝支付"
            confirm-button-text="复制链接"
            cancel-button-text="取消"
            confirm-button-color="#00BCAB"
            cancel-button-color="#AEAEAE"
            v-model-cancel-button="true"
            :message="link"
            @confirm="copyLink($event, { tagId: 'van-dialog2' })"
        />
        <van-dialog
            id="van-dialog2"
            v-model="isShowPayTip"
            title="支付提醒"
            confirm-button-text="去支付"
            cancel-button-text="稍后再看"
            confirm-button-color="#00BCAB"
            cancel-button-color="#AEAEAE"
            v-model-cancel-button="true"
            message="您有订单未支付，请尽快支付"
            @confirm="gotoPay($event, { tagId: 'van-dialog2' })"
        />
    </view>
</template>

<script>
// import vanCell from '@vant/weapp/cell/index';
// import vanCellGroup from '@vant/weapp/cell-group/index';
// import vanCheckbox from '@vant/weapp/checkbox/index';
// import vanPicker from '@vant/weapp/picker/index';
// pages/parkSpaceBooking/parkSpaceBooking.js
import config from './../../utils/config.js';
import util from './../../utils/util.js';
import api from './../../utils/api.js';
// import Dialog from '@vant/weapp/dialog/dialog';
// import Toast from '@vant/weapp/toast/toast';
export default {
    components: {
        // vanCell,
        // vanCellGroup,
        // vanCheckbox,
        // vanPicker
    },
    data() {
        return {
            carNo: '请选择',
            parkTime: '请选择',
            //租赁开始时间
            showCar: false,
            showPark: false,
            checked: true,
            showRulePop: false,
            showStartDate: false,
            datas: {
                parkingName: '',
                parkingRequire: 0,
                spaceNo: '',
                spaceOwnerType: 0,
                phone: '',
                managementMethod: '',
                openTime: '',
                sumDuraTion: ''
            },
            rules1: config.bookparkRules,
            fix: '',
            //0固定 1不固定
            carList: '',
            setMenu1: [
                {
                    text: '包整月,100元/月',
                    id: 2
                },
                {
                    text: '夜间包月18:00—6:00,50元/月',
                    id: 3
                }
            ],
            setMenu2: [
                {
                    text: '包整月,100元/月',
                    id: 2
                }
            ],
            setMenu3: [
                {
                    text: '夜间包月18:00—6:00,50元/月',
                    id: 3
                }
            ],
            setMenu: [],
            nomenu: ['暂不支持包月'],
            showSetmenu: false,
            //套餐
            selectedmenu: '请选择',
            //所选套餐
            columnsTime: [],
            //租赁期限列表
            rentMonth: '请选择',
            //租赁期限
            monthSum: '',
            //租赁期限传参
            showRentmonth: '',
            //租赁弹窗
            minDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000).getTime(),
            maxDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 90).getTime(),
            currentDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000).getTime(),
            rentType: '',
            //选择的套餐号
            productId: '',
            //套餐产品id
            platformRules: config.platformRules,
            link: '',
            //支付宝支付链接,
            showLink: false,
            isShowPayTip: false,
            gotopayType: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const param = JSON.parse(decodeURIComponent(options.param));
        console.log(param);
        let date1 = util.getDate(this.minDate, 'yyyy-MM-dd');
        this.setData({
            datas: param,
            carList: uni.getStorageSync('plateNos').split(','),
            carNo: uni.getStorageSync('plateNos').split(',')[0],
            fix: options.fix,
            maxDate: new Date(this.addmulMonth(date1, 3)).getTime()
        });
        this.composeColumn();
        this.composeSetmenu();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        composeSetmenu() {
            let menu = this.datas.productVOs;
            let setMenu = [];

            if (menu && menu != null && menu.length > 0) {
                menu.map((item) => {
                    if (item.type == '1') {
                        setMenu.push({
                            text: '包整月卡，' + Number(item.unitPrice) / 100 + '元/月',
                            id: 2,
                            productId: item.id
                        });
                    } else if (item.type == '2') {
                        setMenu.push({
                            text: '夜间月卡，' + Number(item.unitPrice) / 100 + '元/月',
                            id: 3,
                            productId: item.id
                        });
                    }
                });
            }

            this.setData({
                setMenu: setMenu
            });
        },

        onChange(event) {
            this.setData({
                checked: event.detail
            });
        },

        submit() {
            if (this.carNo == '请选择') {
                uni.showToast({
                	title:'请选择车辆',
                	icon:'none'
                })
                return;
            }

            if (this.selectedmenu == '请选择') {
				uni.showToast({
					title:'请选择套餐',
					icon:'none'
				})
                return;
            }

            if (this.rentMonth == '请选择') {
				uni.showToast({
					title:'请选择租赁期限',
					icon:'none'
				})
                return;
            }

            if (this.parkTime == '请选择') {
				uni.showToast({
					title:'请选择开始停车时间',
					icon:'none'
				})
                return;
            }

            if (this.checked == false) {
				uni.showToast({
					title:'请勾选同意《停车服务协议》',
					icon:'none'
				})
                return;
            }

            uni.showLoading({
                title: '加载中'
            });
            let param = {
                unionId: uni.getStorageSync('unionId'),
                startTime: this.parkTime,
                spaceNo: this.datas.spaceNo,
                parkingCode: this.datas.parkingCode,
                plateNo: this.carNo,
                manageId: this.datas.id,
                rentedType: this.rentType,
                monthSum: this.monthSum,
                productId: this.productId
            };

            if (this.datas.isAlipay == 1 && this.datas.isWechat == 0) {
                param.payType = '1';
                param.AUTHORIZATION = uni.getStorageSync('AUTHORIZATION');
                uni.hideLoading();
                this.setData({
                    showLink: true,
                    link: encodeURIComponent(JSON.stringify(param))
                });
                uni.requestSubscribeMessage({
                    tmplIds: ['AmeBlYg6oJy-JS7EMelOKy2fxiCJibmeG3GYGLfN0cg', 'zpb7ICpNT9qahTP4_ZWkuLcnNANhfZ2UVnlns2qGqoo', 'cR6ihd_iqKjvTDGkPTfQGE70vn381AP5sQmhAiexvno'],

                    success(sus) {},

                    fail(err) {}
                });
            } else {
                util.request(api.monthBook, param, 'POST')
                    .then((res) => {
                        if (res.success) {
                            uni.hideLoading();

                            if (res.busiCode == 'alipay') {
                                this.setData({
                                    showLink: true,
                                    link: res.data
                                });
                            } else if (res.busiCode == 'wechat' || res.busiCode == 'unionPay') {
                                let param = encodeURIComponent(res.data);
                                uni.showToast({
                                    title: '提交成功'
                                });
                                uni.navigateTo({
                                    url: '../wechatPay/wechatPay?param=' + param  + "&from=01"
                                });
                            } else {
                                Toast(res.msg);
                            }
                        } else if (res.busiCode == 'waitingToPay1') {
                            uni.hideLoading();
                            this.setData({
                                gotopayType: 1,
                                isShowPayTip: true
                            });
                        } else if (res.busiCode == 'waitingToPay2') {
                            uni.hideLoading();
                            this.setData({
                                gotopayType: 2,
                                isShowPayTip: true
                            });
                        } else {
                            uni.hideLoading();
                            Dialog.alert({
                                message: res.msg || '租赁失败，请重试'
                            }).then(() => {
                                // on close
                            });
                        }
                    })
                    .catch((err) => {
                        Toast(err || '接口出错了，请重试');
                    });
            } // let param = {
            //     "unionId": "fb0feca5-0945-4989-b4aa-8c33413ff648",
            //     "startTime": "2021-05-14",
            //     "spaceNo": "A46",
            //     "parkingCode": "a604f6cb-4115-4b6b-b865-7d5f0ba6d4f7",
            //     "plateNo": "浙A123456",
            //     "monthSum": "1",
            //     "manageId": "12",
            //     "rentedType": "2"
            //   }
            // wx.request({
            //   url: 'http://37a886r726.zicp.vip/parking/app/monthReserve',
            //   method:'POST',
            //   data:param,
            //   header:{
            //     Authorization:'b52272a7-7802-4e47-808f-aa9c50513225'
            //   },
            //   success(res){
            //     wx.hideLoading()
            //   if(res.data.busiCode == 'alipay'){
            //     this.setData({
            //       showLink:true,
            //       link:res.data.data
            //     })
            //   }else if(res.data.busiCode == 'wechat'){
            //     let param = encodeURIComponent(res.data.data)
            //     wx.navigateTo({
            //       url:'../wechatPay/wechatPay?param='+param
            //     })
            //   }else{
            //     Toast(res.msg)
            //   }
            //   }
            // })
        },

        /**跳转支付 */
        gotoPay(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            uni.navigateTo({
                url: '../order/index?type=' + this.gotopayType
            });
        },

        findAction(e) {
            if (e) {
                let st = e.indexOf('https');
                let ed = e.indexOf('">');
                let value = e.substring(st, ed);
                return value;
            }

            return e;
        },

        /**
         * copyLink复制链接
         */
        copyLink(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            uni.setClipboardData({
                data: 'https://shareparking.wasu.cn/share-parking/static/pay.html?goto=' + this.link,
                success: () => {
                    this.$emit('close');
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '../order/index?type=2'
                        });
                    }, 10000);
                },
                fail: () => {},
                complete: () => {}
            });
        },

        //展示规则
        showRule() {
            this.setData({
                showRulePop: true
            });
        },

        /**
         * 关闭规则
         */
        closeRule() {
            this.setData({
                showRulePop: false,
                checked: true
            });
        },

        /**
         * 选择停车车辆
         */
        onSelectCar(e) {
            console.log(e);
            this.setData({
                carNo: e.detail.value,
                showCar: false
            });
        },

        showCarFun() {
            this.setData({
                showCar: true
            });
        },

        onCloseCar() {
            this.setData({
                showCar: false
            });
        },

        /**
         * 选择套餐
         */
        onSelectMenu(e) {
            console.log(e);
            this.setData({
                selectedmenu: e.detail.value.text,
                rentType: e.detail.value.id,
                showSetmenu: false,
                productId: e.detail.value.productId
            });
        },

        showSetmenuFun() {
            this.setData({
                showSetmenu: true
            });
        },

        onCloseMenu() {
            this.setData({
                showSetmenu: false
            });
        },

        /**
         * 开始停车时间
         */
        SelectDate(e) {
            console.log(e);
            this.setData({
                showStartDate: false,
                parkTime: util.getDate(e.detail, 'yyyy-MM-dd')
            });
        },

        showStartDateFun() {
            this.setData({
                showStartDate: true
            });
        },

        onCloseDatePop() {
            this.setData({
                showStartDate: false
            });
        },

        /**
         * 选择租赁期限
         */
        onChangeRentMonth(e) {
            this.setData({
                rentMonth: e.detail.value.text,
                monthSum: e.detail.value.id,
                showRentmonth: false
            });
        },

        ShowRentPop() {
            this.setData({
                showRentmonth: true
            });
        },

        onCloseRentMonth() {
            this.setData({
                showRentmonth: false
            });
        },

        /**获取n个月后日期 */
        addmulMonth(date, num) {
            var newDate = new Date(date);
            var year = newDate.getFullYear();
            var month = newDate.getMonth() + num; //获取当前月份的日期

            if (month > 11) {
                for (var i = 0, j = Math.floor(month / 12); i < j; i++) {
                    year++;
                    month -= 12;
                }
            }

            month = parseInt(month + 1);

            if (month < 10) {
                month = '0' + month;
            }

            var date2 = new Date(year, month, 0); //新的年月

            var day1 = newDate.getDate();
            var day2 = date2.getDate();

            if (day1 > day2) {
                //防止+6月后没有31天
                day1 = day2;
            }

            return year + '-' + month + '-' + day1 + '';
        },

        /**
         * 动态生成租赁期限
         */
        composeColumn() {
            let arr = [];

            for (let i = 1; i <= this.datas.sumDuraTion; i++) {
                arr.push({
                    text: i + '个月',
                    id: i
                });
            }

            this.setData({
                columnsTime: arr
            });
        }
    }
};
</script>
<style>
@import './monthlyParking.css';
</style>
